import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SideLayout from '../components/SideLayout';
import {
  Route,
  Switch,
  Redirect,
  withRouter,
  matchPath
} from 'react-router-dom';
import { findNode, findPaths } from '../library/hierarchy';
import RouteContext from '../contexts/RouteContext';
import routes, { mapToPlainRoute } from './routes';

// APP组件，提代路由，当前用户等状态
class App extends Component {
  getCurrentPaths = () => {
    const { location } = this.props;
    return findPaths(routes, item => matchPath(location.pathname, item)).map(
      mapToPlainRoute
    );
  };

  getCurrentRoute = () => {
    const { location } = this.props;
    return (
      mapToPlainRoute(
        findNode(routes, item => matchPath(location.pathname, item))
      ) || {}
    );
  };

  renderRoutes = (routeList, result = []) => {
    routeList.forEach(route => {
      if (route.children) {
        result.push(
          <Redirect
            key={route.key}
            from={route.path}
            to={route.children[0].path}
            exact={route.exact}
          />
        );
        this.renderRoutes(route.children, result);
      } else {
        result.push(
          <Route
            key={route.key}
            path={route.path}
            exact={route.exact}
            component={route.component}
          />
        );
      }
    });
    return result;
  };

  render() {
    return (
      <RouteContext.Provider
        value={{
          currentRoute: this.getCurrentRoute(),
          currentPaths: this.getCurrentPaths(),
          routes: routes
        }}
      >
        <SideLayout>
          <Switch>{this.renderRoutes(routes)}</Switch>
        </SideLayout>
      </RouteContext.Provider>
    );
  }
}

App.propTypes = {
  routes: PropTypes.array
};

App.defaultProps = {
  routes: []
};

export default withRouter(App);
